package com.foreveross.chameleon.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.foreveross.bsl.test.R;
import com.foreveross.chameleon.ModuleManager;
import com.foreveross.chameleon.config.ChameleonConfig;
import com.foreveross.chameleon.config.ChameleonConstants;
import com.foreveross.chameleon.listener.AsyncTaskListener;
import com.foreveross.chameleon.manager.BroadcastManager;
import com.foreveross.chameleon.model.ApplicationInfo;
import com.foreveross.chameleon.model.ModuleInfo;
import com.foreveross.chameleon.task.AppAuthenTask;
import com.foreveross.chameleon.task.UnzipWwwAsyncTask;
import com.foreveross.chameleon.utils.DeviceInfoUtil;
import com.foreveross.chameleon.utils.FileCopeTool;
import com.foreveross.chameleon.utils.PreferencesUtil;
import com.foreveross.chameleon.utils.PropertiesUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * @description 启动界面
 * @author zhouzhineng
 * 
 */
public class SplashActivity extends Activity {

	private final static String TAG = "SplashActivity";
	protected IntentFilter mIntentFilter;
	protected TextView mDialogText;
	protected ProgressBar mProgressBar;
	protected View mSplashBgView;
	private final int INIT_START = 0x0001;
	private final int INIT_FINISH = INIT_START << 1;
	private final int INIT_SUCC = INIT_START << 2;
	private final int INIT_FAIL = INIT_START << 3;
	private final int AUTH_START = 0x0011;
	private final int AUTH_FINISH = AUTH_START << 1;
	private final int AUTH_SUCC = AUTH_START << 2;
	private final int AUTH_FAIL = AUTH_START << 3;
	private Boolean mNeed2SyncLocalInfo = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		init();
	}

	private void init() {

		mDialogText = (TextView) findViewById(R.id.dialog_text);
		if (!isMainModuleExist()) {
			mDialogText.setText(getString(R.string.loading_wait));
		}
		mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
		mSplashBgView = findViewById(R.id.splash_bg);
		boolean isPad = false;
		if (DeviceInfoUtil.isPad()) {
			isPad = true;
		} else {
			isPad = false;
		}
		boolean isPortrait = true;
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			isPortrait = false;
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			isPortrait = true;
		}
		setSplash(isPad, isPortrait);
		ChameleonConfig.NETWORK_OK = isNetworkConnected();
		mIntentFilter = new IntentFilter();
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_INIT_START);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_INIT_FINISH);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_INIT_SUCC);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_INIT_FAIL);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_AUTH_START);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_AUTH_FINISH);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_AUTH_SUCC);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_AUTH_FAIL);
		registerReceiver(mSplashReceiver, mIntentFilter);
		boolean isFirstStart = PreferencesUtil.getInstance(
				getApplicationContext()).isAppFirstStart();
		File installedDir = new File(ChameleonConfig.APP_PATH);
		if (isFirstStart) {
			mNeed2SyncLocalInfo = true;
		}

		if (!installedDir.exists()) {
			installedDir.mkdirs();
		}

		File wwwFile = new File(ChameleonConfig.APP_PATH + "/www.zip");
		if (!wwwFile.exists()) {
			// copy www.zip from assets to sdcard
			UnzipWwwAsyncTask unZipAsynTask = new UnzipWwwAsyncTask(
					getApplicationContext());
			unZipAsynTask.execute("www.zip", ChameleonConfig.APP_PATH
					+ "/www.zip", ChameleonConfig.APP_PATH);
		} else {
			// BroadcastManager.getInstance().send(ChameleonConstants.ACTION_APP_INIT_FINISH);
			refreshResource();
		}

	}

	/**
	 * 刷新资源
	 */
	@SuppressWarnings("static-access")
	private void refreshResource() {
		ApplicationInfo oldAppInfo = ApplicationInfo.getInstance(this);
		if (ChameleonConfig.VERSION_CODE == oldAppInfo.getBuild()) {
			BroadcastManager.getInstance().send(
					ChameleonConstants.ACTION_APP_INIT_FINISH);
			mNeed2SyncLocalInfo = false;
			return;
		} else { // build若低于原先版本安装不会成功,升级的app重新安装资源
			// String mainModuleTag = PropertiesUtil.readProperties(this,
			// R.raw.cube).getString("MAIN_MODULE_IDENTIFY", "");
			// if(!mainModuleTag.equals(oldAppInfo.getMainModuleTag())) {
			// //判断主模块是否需切换
			oldAppInfo.tool.deleteFolder(ChameleonConfig.APP_PATH);
			new File(ChameleonConfig.APP_PATH).mkdirs();
			mNeed2SyncLocalInfo = true;
			UnzipWwwAsyncTask unZipAsynTask = new UnzipWwwAsyncTask(
					getApplicationContext());
			unZipAsynTask.execute("www.zip", ChameleonConfig.APP_PATH
					+ "/www.zip", ChameleonConfig.APP_PATH);
			// } else {
			// BroadcastManager.getInstance().send(ChameleonConstants.ACTION_APP_INIT_FINISH);
			// mNeed2SyncLocalInfo = false;
			// return;
			// }
		}

	}

	protected Handler mSplashHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			int statusCode = msg.what;
			String tip = (String) msg.obj;
			switch (statusCode) {
			case INIT_START:
				mProgressBar.setVisibility(View.VISIBLE);
				mDialogText.setText(R.string.init_start);
				break;
			case INIT_FINISH:
				mProgressBar.setVisibility(View.GONE);
				mDialogText.setText(R.string.init_finish);
				if (mNeed2SyncLocalInfo) {
					ModuleManager.getInstance(SplashActivity.this)
							.syncLocalModuleInfo();
				}
				if (ChameleonConfig.NETWORK_OK) {
					authenApp();
				} else {
					enterMain();
				}

				break;
			case INIT_SUCC:
				mProgressBar.setVisibility(View.GONE);
				mDialogText.setText(R.string.init_succ);
				break;
			case INIT_FAIL:
				mProgressBar.setVisibility(View.GONE);
				mDialogText.setText(R.string.init_fail);
				break;
			case AUTH_START:
				mProgressBar.setVisibility(View.VISIBLE);
				mDialogText.setText(R.string.auth_start);
				break;
			case AUTH_FINISH:
				mProgressBar.setVisibility(View.GONE);
				mDialogText.setText(R.string.auth_finish);
				break;
			case AUTH_SUCC:
				mProgressBar.setVisibility(View.GONE);
				mDialogText.setText(R.string.auth_succ);
				enterMain();
				break;
			case AUTH_FAIL:
				mProgressBar.setVisibility(View.GONE);
				mDialogText.setText(tip);
				showExistDlg(tip);
				break;
			}
			super.handleMessage(msg);
		}

	};

	private void showExistDlg(String tip) {
		Dialog dialog = new AlertDialog.Builder(this)
				.setTitle(getString(R.string.tip))
				.setMessage(tip)
				.setPositiveButton(getString(R.string.btn_ok),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								finish();
							}
						}).create();
		dialog.show();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		registerReceiver(mSplashReceiver, mIntentFilter);
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(mSplashReceiver);
		super.onDestroy();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		boolean isProtrait = true;
		boolean isPad = DeviceInfoUtil.isPad();
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			isProtrait = false;
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			isProtrait = true;
		}
		setSplash(isPad, isProtrait);
	}

	private BroadcastReceiver mSplashReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context content, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(ChameleonConstants.ACTION_APP_AUTH_START)) {

			} else if (action.equals(ChameleonConstants.ACTION_APP_AUTH_FINISH)) {

			} else if (action.equals(ChameleonConstants.ACTION_APP_AUTH_SUCC)) {

			} else if (action.equals(ChameleonConstants.ACTION_APP_AUTH_FAIL)) {

			} else if (action.equals(ChameleonConstants.ACTION_APP_INIT_START)) {

			} else if (action.equals(ChameleonConstants.ACTION_APP_INIT_FINISH)) {
				mSplashHandler.sendEmptyMessage(INIT_FINISH);
			} else if (action.equals(ChameleonConstants.ACTION_APP_INIT_SUCC)) {

			} else if (action.equals(ChameleonConstants.ACTION_APP_INIT_FAIL)) {

			}
		}

	};

	/**
	 * app 鉴权
	 */
	private void authenApp() {
		AppAuthenTask authenTask = new AppAuthenTask(this,
				new AsyncTaskListener() {

					@Override
					public void onSucc(String result) {
						// TODO Auto-generated method stub
						try {
							JSONObject json = new JSONObject(result);
							String token = json.getString("token");
							String expired = json.getString("expired");

							// 保存token和expired
							ChameleonConfig.addConfigAfterAppAuth(token);
							Message mg = new Message();
							mg.what = AUTH_SUCC;
							mg.obj = getString(R.string.auth_succ);
							mSplashHandler.sendMessage(mg);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					@Override
					public void onFail(int errcode) {
						// TODO Auto-generated method stub
						Message ms = new Message();
						ms.what = AUTH_FAIL;
						if (errcode == 520) {
							ms.obj = "应用不存在";
						} else {
							ms.obj = getString(R.string.auth_fail);
						}
						mSplashHandler.sendMessage(ms);
					}

				});
		authenTask.exec();
	}

	private void enterMain() {
		mProgressBar.setVisibility(View.VISIBLE);
		Intent it = new Intent(SplashActivity.this, MainActivity.class);
		if (isNetworkConnected()) {
			it.putExtra(ChameleonConstants.NETWORK_STATE, true);
		} else {
			it.putExtra(ChameleonConstants.NETWORK_STATE, false);
		}
		startActivity(it);
		SplashActivity.this.finish();

	}

	protected boolean isMainModuleExist() {
		boolean isExist = false;
		return isExist;
	}

	/**
	 * splash_phone_l //手机横屏 splash_phone_p //手机竖屏 splash_pad_l //pad横屏
	 * splash_pad_p //pad竖屏
	 * 
	 * @param isPad
	 *            是否pad true pad false phone
	 * @param isPortrait
	 *            是否竖屏 true 竖屏 false 横屏
	 * **/
	private void setSplash(boolean isPad, boolean isPortrait) {

		String res = null;
		if (isPortrait) {
			if (isPad) {
				res = "splash_pad_p";
			} else {
				res = "splash_phone_p";
			}
		} else {
			if (isPad) {
				res = "splash_pad_l";
			} else {
				res = "splash_phone_l";
			}
		}
		int resID = getResources().getIdentifier(res, "drawable",
				getPackageName());
		if (resID > 0) {
			mSplashBgView.setBackgroundResource(resID);
		}
	}

	public boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return ni != null && ni.isConnectedOrConnecting();
	}
}
